package com.shangyueshang.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

/**
 * @author JokeyFeng
 * @date: 2023/8/5 10:45
 * @project: shangyueshang
 * @package: com.shangyueshang.converter
 * @comment:
 */
public class YearMonthConverter implements Converter<YearMonth> {
	
	@Override
	public Class supportJavaTypeKey() {
		return YearMonth.class;
	}
	
	@Override
	public CellDataTypeEnum supportExcelTypeKey() {
		return CellDataTypeEnum.STRING;
	}
	
	@Override
	public YearMonth convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
		if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
			return YearMonth.parse(cellData.getStringValue());
		} else {
			return YearMonth.parse(
					cellData.getStringValue(),
					DateTimeFormatter.ofPattern(
							contentProperty.getDateTimeFormatProperty().getFormat()
					)
			);
		}
	}
	
	@Override
	public CellData convertToExcelData(YearMonth value, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
		return new CellData(value.toString());
	}
}
